#include <sstream>

#include "./SessionManager.h"

std::shared_ptr<Session> SessionManager::getSession(const HttpRequest &req, HttpResponse *res)
{
    std::shared_ptr<Session> session{};

    std::string id = this->getSessionIdFromRequestCookie(req);
    if (!id.empty())
    {
        session = this->storage_->load(id);
    }

    if (!session || session->isExpired())
    {
        id = this->generateSessionId();
        session = std::make_shared<Session>(this, id);
        this->setSessionIdToResponseCookie(id, res);
    }
    else // 为现有会话设置管理器
    {
        session->setManager(this);
    }

    session->refreshExpiryTime();
    this->storage_->save(session);

    return session;
}

std::string SessionManager::getSessionIdFromRequestCookie(const HttpRequest &req)
{
    std::string id{};

    std::string cookie = req.getHeader("Cookie");
    if (cookie.empty())
    {
        return id;
    }

    size_t begin = cookie.find("id=");
    if (begin == std::string::npos)
    {
        return id;
    }

    begin += 3; // 跳过“id=”
    size_t end = cookie.find(';', begin);
    if (end == std::string::npos)
    {
        id = cookie.substr(begin);
    }
    else
    {
        id = cookie.substr(begin, end - begin);
    }
    return id;
}

std::string SessionManager::generateSessionId()
{
    std::stringstream ss{};
    std::uniform_int_distribution<> dist(0, 15); // 0-15均匀分布随机整数
    for (int i = 0; i < 32; ++i)                 // 32个字符，每个字符是一个十六进制数字
    {
        ss << std::hex << dist(this->randomGen_);
    }
    return ss.str();
}

void SessionManager::setSessionIdToResponseCookie(const std::string &id, HttpResponse *res)
{
    std::string cookie = "id=" + id + "; Path=/; HttpOnly";
    res->addHeader("Set-Cookie", cookie);
}